package com.uzhie.jt808.task;

import com.uzhie.jt808.JT808SysCache;
import com.uzhie.util.CacheManager;
import io.netty.buffer.ByteBufUtil;
import org.apache.log4j.Logger;

import java.util.concurrent.Callable;

/**
 * Created by TangFei on 2018/9/17.
 * 平台指令下发 阻塞等待终端响应
 */
public class TaskCommonWait implements Callable<byte[]> {

    private Logger logger = Logger.getLogger(getClass());

    // 缓存 key
    private String key;
    // 存储 key - 终端响应结果
    private CacheManager<String, byte[]> cacheManager;
    // 存储 key - 对象锁
    private JT808SysCache<String, Thread> sysCache;

    public TaskCommonWait(String key, CacheManager<String, byte[]> cacheManager, JT808SysCache<String, Thread> sysCache) {
        this.key = key;
        this.cacheManager = cacheManager;
        this.sysCache = sysCache;
    }

    @Override
    public byte[] call() throws Exception {
        Thread thread = Thread.currentThread();
        sysCache.putCacheVal(key, thread);
        synchronized (thread) {
            logger.trace("wait lock is " + thread + " 等待终端响应 最大等待时长 30s");
            try {
                thread.wait(30 * 1000L);
                byte[] bytes = cacheManager.get(CacheManager.DES.SYS_CACHE, key, byte[].class);
                cacheManager.remove(CacheManager.DES.SYS_CACHE, key);
                sysCache.remove(key);
                logger.trace("移除 key : " + key);
                logger.trace("获取到终端响应结果为：" + ByteBufUtil.hexDump(bytes));
                return bytes;
            } catch (InterruptedException e) {
                logger.error("等待线程被中断！", e);
                return new byte[]{};
            }
        }
    }
}
